﻿<div class="pear-social">
    <div class="pear-social-side">
        <div class="pear-social-avatar">
            <img src="@Url.Action("GetProfilePicture","Users")" />
        </div>
        <div class="pear-social-control">
            <div pear-id="1" class="layui-this layui-icon layui-icon-dialogue"></div>
        </div>
        <div class="pear-social-setting layui-icon layui-icon-slider"></div>
    </div>
    <div class="pear-social-list">
        <div class="pear-social-list-header">
            <input type="text" class="search" />
            <div class="searchBtn layui-icon layui-icon-add-1"></div>
        </div>
        <div class="pear-social-list-body">
            <div class="layui-side-scroll" style="width: 100%;">
                <div pear-id="1" class="body layui-side-scroll session" id="userList"></div>
            </div>
        </div>
    </div>
    <div class="pear-social-body" data-currUserId="">
        <div class="pear-social-body-header">
            <div class="title"></div>
        </div>
        <div class="pear-social-body-content">
            <div class="pear-social-body-content-chat" id="chatContent" style="overflow:auto;">
                <ul class="content"></ul>
            </div>
            <div class="pear-social-body-content-input">
                <div class="pear-social-body-content-input-tool">
                    <a class="layui-icon layui-icon-face-smile"></a>
                    <a class="layui-icon layui-icon-email"></a>
                    <a class="layui-icon layui-icon-dialogue"></a>
                    <a class="layui-icon layui-icon-time"></a>
                </div>
                <textarea id="socalContent"></textarea>
                <button class="pear-btn pear-btn-md pear-social-body-content-input-enter" data-type="send">发 送</button>
            </div>
        </div>
    </div>
</div>

<script id="userTemplate" type="text/html">
    <div class="body-item" data-id="{{ d.id }}" data-name="{{ d.userName }}">
        <img class="body-item-avatar" src="{{ d.userAvatar }}">
        <span class="body-item-name">{{ d.userName }}</span>
        <span class="dot {{d.isOnline?'online':''}}"></span>
        <span class="layui-badge" style="{{ d.unreadMessageCount > 0?'':'display:none;' }}">{{ d.unreadMessageCount > 0?d.unreadMessageCount:''}}</span>
    </div>
</script>

<script id="messageTemplate" type="text/html">
    <li class="{{ d.side==1? 'me':'other' }}">
        <img src="{{ d.userAvatar }}" title="{{ d.userName }}">
        <span>{{ d.message }}</span>
        <div style="clear:both;">
            <label style="font-size:smaller;float:right; margin-right:40px;margin-top:2px;">{{ layui.util.toDateString(d.creationTime, "yyyy/MM/dd HH:mm:ss") }}</label>
        </div>
    </li>
</script>

@section scripts{
    <script src="~/libs/signalr/signalr.js" asp-append-version="true"></script>
    <script type="text/javascript">
        layui.use(['abp','table', 'element', 'laytpl','abpsignalrclient','abpsignalrchat'], function () {
            var $ = layui.$;
            var abp = layui.abp;
            var element = layui.element;
            var laytpl = layui.laytpl;
            var app = layui.abpsignalrchat;

            var userList = {};

            //加载userList
            var loadChatUser = function () {
                abp.ajax({
                    url: "@Url.Action("GetChatUserList", "Chat")",
                    type: "Get",
                    abpHandleError: false
                }).done(function (data) {
                    if (data.code == 200) {
                        layui.each(data.data, function (index, item) {
                            data.data[index].userAvatar = "@Url.Action("GetProfilePictureByUser","Users")" + abp.utils.formatString("?id={0}", data.data[index].id);
                            laytpl(userTemplate.innerHTML).render(data.data[index], function (html) {
                                $("#userList").append(html);
                            });
                        });
                        userList = data.data;
                    }
                }).fail(function (jqXHR) {
                    layer.msg(jqXHR.message, { icon: 5 });
                });
            }
            loadChatUser();

            //加载messageList
            var loadUserChatMessage = function (currUserId) {
                abp.ajax({
                    url: "@Url.Action("GetUserChatMessageList", "Chat")" + abp.utils.formatString("?userId={0}", currUserId),
                    type: "Get",
                    abpHandleError: false
                }).done(function (data) {
                    if (data.code != 200) {
                        return;
                    }

                    layui.each(data.data, function (index, item) {
                        data.data[index].userAvatar = "@Url.Action("GetProfilePictureByUser","Users")" + abp.utils.formatString("?id={0}", data.data[index].side == 1 ? data.data[index].userId : data.data[index].targetUserId);
                        data.data[index].userName = data.data[index].side == 1 ? data.data[index].userId : data.data[index].targetUserId;
                        laytpl(messageTemplate.innerHTML).render(data.data[index], function (html) {
                            $(".pear-social-body-content .content").prepend(html);
                        });
                    });

                    var e = document.getElementById("chatContent");
                    e.scrollTop = e.scrollHeight;
                    //$(".pear-social-body-content-chat").animate({ "scrollTop": $(".pear-social-body-content-chat")[0].scrollHeight }, 0);
                }).fail(function (jqXHR) {
                    layer.msg(jqXHR.message, { icon: 5 });
                });
            }

            //设置未读消息为已读
            var markAllUnreadMessagesOfUserAsRead = function (currUserId) {
                abp.ajax({
                    url: "@Url.Action("MarkAllUnreadMessagesOfUserAsRead", "Chat")" + abp.utils.formatString("?userId={0}", currUserId),
                    type: "Get",
                    abpHandleError: false
                }).fail(function (jqXHR) {
                    layer.msg(jqXHR.message, { icon: 5 });
                });
            };

            //点击菜单，切换菜单项
            $(".pear-social .pear-social-control").on("click", "div", function () {
                var toolId = $(this).attr("pear-id");

                $(".pear-social .body").css({
                    display: "none"
                });
                $(".pear-social .body[pear-id='" + toolId + "']").css({
                    display: "block"
                });

                $(".pear-social .pear-social-control div").removeClass("layui-this");
                $(this).addClass("layui-this");
            });

            //点击用户列表，切换对话
            $(".layui-side-scroll .session").on("click", "div", function () {
                var userId = $(this).attr("data-id");
                var currUserId = $(".pear-social-body").attr("currUserId");

                if (userId == currUserId) {
                    return;
                }

                $(".pear-social-body").attr("currUserId", userId);
                $(".pear-social-body-header .title").text($(this).attr("data-name"));
                $(".pear-social-body-content .content").html("");
                $("#socalContent").html("");

                loadUserChatMessage(userId);
                markAllUnreadMessagesOfUserAsRead(userId);
            });

            //监听消息
            abp.event.on('app.chat.messageReceived', function (message) {
                console.log(message);
                var currUserId = $(".pear-social-body").attr("currUserId");
                if (currUserId != undefined && currUserId == message.targetUserId) {
                    var data = {
                        message: message.message,
                        side: message.side,
                        userAvatar: "@Url.Action("GetProfilePictureByUser","Users")" + abp.utils.formatString("?id={0}", message.side == 1 ? message.userId : message.targetUserId),
                        userName: message.side == 1 ? message.userId : message.targetUserId
                    };
                    laytpl(messageTemplate.innerHTML).render(data, function (html) {
                        $(".pear-social-body-content .content").append(html);
                    });
                    $(".pear-social-body-content-chat").animate({ "scrollTop": $(".pear-social-body-content-chat")[0].scrollHeight }, 400);
                    markAllUnreadMessagesOfUserAsRead(message.targetUserId);
                    return;
                }

                if (message.side != 1) {
                    for(var i = 0;i< userList.length;i++){
                        if(userList[i].id==message.targetUserId) {
                            userList[i].unreadMessageCount += 1;
                            $("[data-id='" + message.targetUserId + "']")
                                .children(".layui-badge")
                                .css("display","inline")
                                .text(userList[i].unreadMessageCount);
                            break;
                        }
                    }
                }
            });

            //监听阅读状态改变
            abp.event.on('app.chat.allUnreadMessagesOfUserRead', function (data) {
                console.log("allUnreadMessagesOfUserRead 0k");
                for(var i = 0;i< userList.length;i++) {
                    if(userList[i].id==data.friend.userId) {
                        userList[i].unreadMessageCount = 0;
                        $("[data-id='" + data.friend.userId + "']")
                            .children(".layui-badge")
                            .css("display","none")
                            .text('');
                        break;
                    }
                }
            });

            //监听用户在线状态改变
            abp.event.on('app.chat.userConnectionStateChanged', function (data) {
                console.log("userConnectionStateChanged Ok");
                var onlineStatusElement = $("[data-id='" + data.friend.userId + "']").children(".dot");
                if(data.isConnected){
                    onlineStatusElement.addClass("online");
                }
                else{
                    onlineStatusElement.removeClass("online");
                }
            });

            //回车发送内容
            $('#socalContent').bind('keypress', function (event) {
                if (event.keyCode == "13") {
                    event.preventDefault();
                    sendMessage();
                }
            });

            //执行发送内容
            window.sendMessage = function () {
                var currUserId = $(".pear-social-body").attr("currUserId");
                if (currUserId == undefined || currUserId == "") {
                    return false;
                }

                var messageContent = $("#socalContent").val();
                if (messageContent == "") {
                    return false;
                }

                app.chat.sendMessage({
                    tenantId: @AbpSession.TenantId,
                    userId: parseInt(currUserId),
                    message: messageContent
                }, function () {
                    $("#socalContent").val("");
                });
            }

            //监听页面主按钮操作
            var active = {
                send: function () {
                    sendMessage();
                }
            };

            //点击事件转发器
            $('.pear-btn').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });
        });
    </script>
}

